package com.steven.design.JieGou_Pattern.daili.dongtai;

import com.steven.design.JieGou_Pattern.daili.CommonMan;
import com.steven.design.JieGou_Pattern.daili.Man;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {

    private CommonMan commonMan;

    public Man getInstance(CommonMan commonMan){
        this.commonMan=commonMan;
       return (Man) Proxy.newProxyInstance(commonMan.getClass().getClassLoader(),commonMan.getClass().getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object obj = null;
        if(method.getName().equals("eat")){
            System.out.println("吃之前喝点酒");
            obj =  method.invoke(commonMan,args);
            System.out.println("吃完之后聊天");
        }else if(method.getName().equals("sleep")){
            System.out.println("睡之前玩手机");
            obj =  method.invoke(commonMan,args);
            System.out.println("睡后做梦");
        }
        return obj;
    }


    public static void main(String[] args) {
        CommonMan commonMan = new CommonMan();
        Man instance = new DynamicProxy().getInstance(commonMan);
        instance.eat();
        instance.sleep();
    }
}
